package db.migration;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.CharEncoding;
import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.*;

/**
 * 定义Jave自定义脚本创建基类
 */
public abstract class BaseInitScript implements SpringJdbcMigration {

    private static final Logger logger = LoggerFactory.getLogger(BaseInitScript.class);

    /**
     * 初始化数据文件存放路径
     */
    public static final String DATA_PATH = "data/";

    @Override
    public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * 读取本地文件
     *
     * @Param: filePath 相对于classpath的目录
     * @return: 输出本地文件字节数组
     */
    public String getContentByFilePath(String filePath) {
        InputStream in = null;
        String ret;
        try {
            in = this.getClass().getClassLoader().getResourceAsStream(filePath);
            ret = IOUtils.toString(in, CharEncoding.UTF_8);
            return ret;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        return "";
    }

    /**
     * 读取本地文件
     *
     * @Param: filePath
     * @return: 输出本地文件字节数组
     */
    public byte[] getContentByteByFilePath(String filePath) {
        InputStream in = null;
        in = this.getClass().getClassLoader().getResourceAsStream(filePath);
        byte[] bb = null;
        try {
            bb = IOUtils.toByteArray(in);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
        return bb;
    }


    /**
     * 读取本地文件
     *
     * @Param: file
     * @return: 输出本地文件字节数组
     */
    public String getContentByteByFile(File file) {
        String result = "";
        BufferedReader br = null;
        try {
            //构造一个BufferedReader类来读取文件
            br = new BufferedReader(new FileReader(file));
            result = IOUtils.toString(br);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(br);
        }
        return result;
    }
}
